import router from "./router";
import store from "./store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getToken, removeToken } from "@/utils/auth";
import { getRedirect } from "@/utils/index";

NProgress.configure({ showSpinner: false });

const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.query.token) removeToken();
  if (getToken()) {
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        let pathName = window.location.pathname;
        store.dispatch("getMenuTree").then(accessRoutes => {
          store.commit("SET_ROLES", ["ROLE_DEFAULT"]);
          router.addRoutes(accessRoutes); // 动态添加可访问路由表
          next({ path: pathName, replace: true }); // hack方法 确保addRoutes已完成
        });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      if (to.query.token != undefined) {
        let { token } = to.query;
        store.dispatch("SysLogin", { token }).then(() => {
          setTimeout(() => {
            next("/");
          }, 2000);
        });
        return;
      }
      window.location.href =
        (process.env.NODE_ENV == "production"
          ? getRedirect()
          : "http://ucs.test.readline.cn") +
        `?redirectUrl=${encodeURIComponent(location.origin)}`;
      NProgress.done();
      return;
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
